package com.vercon.moensmart.dialog

import android.graphics.Bitmap
import android.util.DisplayMetrics
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.google.gson.Gson
import com.vercon.common.presenter.common.MirrorResultView
import com.vercon.moensmart.R
import com.vercon.moensmart.adapter.HealthDetailsTabAdapter
import com.vercon.moensmart.adapter.base.BaseAdapter
import com.vercon.moensmart.databinding.DialogHealthDetailsLayoutBinding
import com.vercon.moensmart.dialog.base.BaseDialogFragment
import com.vercon.moensmart.mode.HealthChartDate
import com.vercon.moensmart.mode.HealthChartDate2
import com.vercon.moensmart.mode.HealthChartDate3
import com.vercon.moensmart.mode.HealthMeasureTarget
import com.vercon.moensmart.mode.response.BaseResponse
import com.vercon.moensmart.mode.response.HealthMeasure
import com.vercon.moensmart.mode.response.MeasureTrendChart
import com.vercon.moensmart.presenter.MoenPresenter
import com.vercon.moensmart.viewmodel.SystemViewModel
import java.text.SimpleDateFormat
import java.util.Date


class HealthDetailsDialog : BaseDialogFragment<DialogHealthDetailsLayoutBinding>() {

    var systemViewModel : SystemViewModel? = null
    var healthDetailsTabAdapter : HealthDetailsTabAdapter? = null
    var currenSelectTab : String? = null
    val moenPresenter = MoenPresenter()
    val sdf = SimpleDateFormat("yyyy-MM-dd")
    var create_time : String? = "--"
    var currentBodyType : Float = 0.0f
    var userId : String? = null
    companion object{
        val CURRENT_TAB = "CURRENT_TAB"
    }

    override fun onStart() {
        super.onStart()
        val dm = DisplayMetrics()
        activity?.windowManager?.defaultDisplay?.getMetrics(dm)
        dialog!!.window!!.setLayout(resources.getDimension(com.vercon.common.R.dimen.dp_1037).toInt(), resources.getDimension(com.vercon.common.R.dimen.dp_1080).toInt())
    }

    override fun onCreateViewBinding(inflater: LayoutInflater, parent: ViewGroup?): DialogHealthDetailsLayoutBinding {
       return DialogHealthDetailsLayoutBinding.inflate(inflater,parent,false)
    }

    override fun initView(view: View?) {
        systemViewModel = ViewModelProvider(requireActivity())[SystemViewModel::class.java]
        binding?.webviewEcharts?.setBackgroundColor(0)
        binding?.webviewEcharts?.background?.alpha = 0
        healthDetailsTabAdapter = HealthDetailsTabAdapter(context)
        binding?.healthTargetTabRecyclerView?.adapter = healthDetailsTabAdapter

        currenSelectTab = arguments?.getString(CURRENT_TAB,"")

    }

    override fun initListener(view: View?) {
        healthDetailsTabAdapter?.setItemOnClickListener(object : BaseAdapter.BaseItemListener<HealthMeasureTarget?>{
            override fun onItemClickListener(v: View?, data: HealthMeasureTarget?, position: Int) {
                currenSelectTab = data?.type
                setNewDataUI(data)
                selectDate(1)
            }
        })
        systemViewModel?.healthMeasureLiveData?.observe(this@HealthDetailsDialog,object : Observer<HealthMeasure> {
            override fun onChanged(value: HealthMeasure) {
                try {
                    val data = Gson().fromJson(value?.list?.get(0)?.log_content, HealthMeasure.LogContent::class.java)
                    healthDetailsTabAdapter!!.setData(HealthMeasureTarget.getShowListDialog(data))
                    healthDetailsTabAdapter!!.setCurrentTab(currenSelectTab!!)
                    create_time =  sdf.format(Date(sdf.parse( value.list[0].create_time).time))
                    binding?.tvValueUpdateTime?.text = create_time


                    for ((i,bean) in healthDetailsTabAdapter!!.list.withIndex()){
                        if(bean?.type.equals(currenSelectTab)){
                            setNewDataUI(bean)
                            binding?.healthTargetTabRecyclerView?.scrollToPosition(i)
                        }
                        if(bean?.type.equals(HealthMeasureTarget.body_type)){
                            currentBodyType = bean?.realValue!!
                        }
                    }
                    selectDate(1)
                }catch (e : Exception){
                    e.printStackTrace()
                }
            }
        })

        val user_id =  systemViewModel?.currentUserIdLiveData?.value
        userId = if(systemViewModel?.loginUserId.equals(user_id)) null else user_id


        binding?.tvSelectDayData?.setOnClickListener { selectDate(1) }
        binding?.tvSelectWeekData?.setOnClickListener { selectDate(2) }
        binding?.tvSelectMonthData?.setOnClickListener { selectDate(3) }
        binding?.tvSelectYearData?.setOnClickListener { selectDate(4) }

        binding?.igClose?.setOnClickListener {
            dismiss()
        }
    }

    private fun setNewDataUI(data : HealthMeasureTarget?){
        binding?.tvValue?.text = data?.value + data?.unit
        binding?.tvAveValue?.text = "--"
        binding?.tvValueUpdateTime?.text = "--"
        when(currenSelectTab){
            HealthMeasureTarget.WEIGHT->{
                binding?.tvValueUpdateTime?.text = create_time
                binding?.llNormalAbnormal?.visibility = View.GONE
                binding?.rlOtherProgress?.visibility = View.GONE
                binding?.igHealthValueLocation?.visibility = View.GONE
                binding?.tvValueState?.visibility = View.GONE
                binding?.llChangeDayOfChart?.visibility = View.VISIBLE
                binding?.tvValue?.textSize = resources.getDimension(com.vercon.common.R.dimen.sp_58)
                binding?.igBodyType?.visibility =  View.GONE

            }
            HealthMeasureTarget.body_type->{
                binding?.llNormalAbnormal?.visibility = View.GONE
                binding?.rlOtherProgress?.visibility = View.GONE
                binding?.igHealthValueLocation?.visibility = View.GONE
                binding?.tvValueState?.visibility = View.GONE
                binding?.llChangeDayOfChart?.visibility = View.GONE
                binding?.tvValue?.textSize = resources.getDimension(com.vercon.common.R.dimen.sp_30)

                binding?.tvValueUpdateTime?.text = "BMI"
                binding?.tvAveValue?.text = "你的BMI:" + data?.value
                binding?.igBodyType?.visibility =  View.VISIBLE
                data?.bodyTypePic?.let { binding?.igBodyType?.setImageResource(it) }

                getChartData(1)

            }else->{
                binding?.tvValueUpdateTime?.text = create_time

                binding?.llNormalAbnormal?.visibility = View.VISIBLE
                binding?.rlOtherProgress?.visibility = View.VISIBLE
                binding?.igHealthValueLocation?.visibility = View.VISIBLE
                binding?.tvValueState?.visibility = View.VISIBLE
                binding?.llChangeDayOfChart?.visibility = View.VISIBLE
                binding?.tvValue?.textSize = resources.getDimension(com.vercon.common.R.dimen.sp_58)

                binding?.tvValueState?.text = if (data?.isNormal!!) "正常" else "异常"
                binding?.tvMinNormalValue?.text = data.min.toString()
                binding?.tvMaxNormalValue?.text = data.max.toString()
                binding?.igBodyType?.visibility =  View.GONE

                val layoutParams: RelativeLayout.LayoutParams = binding?.igHealthValueLocation?.layoutParams as RelativeLayout.LayoutParams
                if(data.isNormal){
                    binding?.igHealthValueLocation?.setImageResource(R.mipmap.ic_health_value_normal_p)
                    var baseX = resources.getDimension(com.vercon.common.R.dimen.dp_120).toInt()
                    var normalX = resources.getDimension(com.vercon.common.R.dimen.dp_480).toInt()
                    layoutParams.leftMargin = (( (data.realValue - data.min )/ (data.max - data.min)) * normalX).toInt() + baseX
                }else{
                    binding?.igHealthValueLocation?.setImageResource(R.mipmap.ic_health_value_abnormal_p)
                    if(data.realValue > data.max){
                        layoutParams.leftMargin = resources.getDimension(com.vercon.common.R.dimen.dp_660).toInt()
                    }else{
                        layoutParams.leftMargin = resources.getDimension(com.vercon.common.R.dimen.dp_40).toInt()
                    }
                }
                binding?.igHealthValueLocation?.layoutParams = layoutParams
            }
        }

    }

    private fun getChartData(type : Int){
        var day_week_month_year : String? = null
        when(type){
            1->{ day_week_month_year = "day" }
            2->{ day_week_month_year = "week" }
            3->{ day_week_month_year = "month" }
            4->{ day_week_month_year = "year" }
        }

        binding?.webviewEcharts?.setWebViewClient(WebViewClient())
        when(currenSelectTab){
            HealthMeasureTarget.body_type->{
                binding?.webviewEcharts?.init("file:///android_asset/EChartViewBody.html")
                val xLabel = ArrayList<String>()
                xLabel.add("偏瘦")
                xLabel.add("标准")
                xLabel.add("偏胖")
                xLabel.add("肥胖")
                val yData = ArrayList<Float>()
                val healthChartDate = HealthChartDate3()
                when(currentBodyType ){
                    1.0f->{  yData.add(4.0f) }
                    2.0f->{  yData.add(3.0f) }
                    3.0f->{  yData.add(2.0f) }
                    4.0f->{  yData.add(1.0f) }
                }
                healthChartDate.yLabel = yData
                healthChartDate.xLabel = xLabel
                binding?.webviewEcharts?.setWebViewClient(object : WebViewClient() {
                    override fun onPageFinished(view: WebView, url: String) {
                        super.onPageFinished(view, url)
                        binding?.webviewEcharts?.refreshEchartsWithOption(healthChartDate)
                    }
                    override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
                        super.onPageStarted(view, url, favicon)
                    }
                })
            }else->{

                    if("day".equals(day_week_month_year)){
                        binding?.webviewEcharts?.init("file:///android_asset/EChartViewTime.html")
                    }else{
                        binding?.webviewEcharts?.init("file:///android_asset/EChartView.html")
                    }

                moenPresenter.getMeasureTrendChart(day_week_month_year,null,null,null,null,userId,
                    object : MirrorResultView<BaseResponse<MeasureTrendChart>> {
                        override fun onSuccess(result: BaseResponse<MeasureTrendChart>?) {
                            try {
                                if(result?.data?.ave_value == null || result?.data?.ave_value.equals("{}")){
                                    binding?.tvAveValue?.text = "平均" + HealthMeasureTarget.getName(currenSelectTab) + ": --"
                                }else{
                                    val aveValue = Gson().fromJson(result?.data?.ave_value, MeasureTrendChart.aveValueBean::class.java)
                                    binding?.tvAveValue?.text = "平均" + aveValue.getValue(currenSelectTab).toString()
                                }

                                var healthChartDate: Any? = null
                                if("day".equals(day_week_month_year)){
                                    val xLabel = ArrayList<String>()
                                    val yData = ArrayList<Any>()
                                    for((i,bean) in result?.data?.list?.withIndex()!!){
                                        val array = arrayOfNulls<Any>(2)
                                        array[0] = bean.name
                                        if(bean.value != null){
                                            val value = Gson().fromJson(bean.value, MeasureTrendChart.valueBean::class.java)
                                            array[1] = value.getValue(currenSelectTab).toInt()
                                            yData.add(array)
                                        }else{
                                            array[1] = 0
                                            yData.add(array)
                                        }
                                    }
                                    if(yData.size == 0){
                                        //造一个假数据
                                        for ( i in 0..5) {
                                            val array = arrayOfNulls<Any>(2)
                                            if(i > 2){
                                                array[0] = sdf.format(Date()) + " " + (i*4).toString() +":00"
                                            }else{
                                                array[0] = sdf.format(Date()) +" 0" +(i*4).toString() +":00"
                                            }
                                            array[1] = 0
                                            yData.add(array)
                                        }
                                    }
                                    healthChartDate = HealthChartDate()
                                    healthChartDate.Data = yData
                                    healthChartDate.xLabel = xLabel
                                    binding?.webviewEcharts?.init("file:///android_asset/EChartViewTime.html")
                                }else{
                                    val xLabel = ArrayList<String>()
                                    val yData = ArrayList<Int>()
                                    for((i,bean) in result?.data?.list?.withIndex()!!){
                                        xLabel.add(MeasureTrendChart.xLabel(day_week_month_year,i))
                                        if(bean.value != null){
                                            val value = Gson().fromJson(bean.value, MeasureTrendChart.valueBean::class.java)
                                            yData.add(value.getValue(currenSelectTab).toInt())
                                        }else{
                                            yData.add(0)
                                        }
                                    }
                                    healthChartDate = HealthChartDate2()
                                    healthChartDate.Data = yData
                                    healthChartDate.xLabel = xLabel
                                    binding?.webviewEcharts?.init("file:///android_asset/EChartView.html")
                                }
                                binding?.webviewEcharts?.setWebViewClient(object : WebViewClient() {
                                    override fun onPageFinished(view: WebView, url: String) {
                                        super.onPageFinished(view, url)
                                        binding?.webviewEcharts?.refreshEchartsWithOption(healthChartDate)
                                    }
                                    override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
                                        super.onPageStarted(view, url, favicon)
                                    }
                                })

                            }catch (e:Exception){
                                e.printStackTrace()
                            }
                        }
                        override fun onError(code: Int, message: String?) {

                        }
                    })
            }
        }

    }



    private fun selectDate(type : Int){
        getChartData(type)
        binding?.tvSelectDayData?.let { selectDateStyle(false, it) }
        binding?.tvSelectWeekData?.let { selectDateStyle(false, it) }
        binding?.tvSelectMonthData?.let { selectDateStyle(false, it) }
        binding?.tvSelectYearData?.let { selectDateStyle(false, it) }
        when(type){
            1->{ binding?.tvSelectDayData?.let { selectDateStyle(true, it) } }
            2->{ binding?.tvSelectWeekData?.let { selectDateStyle(true, it) } }
            3->{ binding?.tvSelectMonthData?.let { selectDateStyle(true, it) } }
            4->{ binding?.tvSelectYearData?.let { selectDateStyle(true, it) } }
        }
    }

    private fun selectDateStyle(isSelected : Boolean,tv : TextView){
        if(isSelected){
            tv.setBackgroundResource(R.drawable.bg_health_target_data_date)
            tv.setTextColor(resources.getColor(R.color.white))
        }else{
            tv.setBackgroundResource(0)
            tv.setTextColor(resources.getColor(com.vercon.common.R.color.color_99B5BC))
        }
    }

    override val isFullScreen: Boolean
        get() = false

}